import axios from 'axios';
import { userService } from './userService';

const api = axios.create({
  baseURL: '/api', // 使用相对路径，会被 Vite 代理
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 添加认证token到请求头
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export const authService = {
  async login(username, password) {
    try {
      const response = await api.post('/chat_login', { username, password })
      if(response.data.code === 200) {
        const token = response.data.data.token
        userService.setToken(token)
        return token
      }else{
        throw new Error(response.data.msg || '未知错误')
      }
      
    } catch (error) {
      throw new Error(error.message || '未知错误')
    }
  },

  logout() {
    userService.clearUser()
  }
}

export const messageService = {
  async uploadImage(file) {
    const formData = new FormData();
    formData.append('image', file);
    const response = await api.post('/upload', formData);
    return response.data.url;
  }
};